<template>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <!-- 其他表单项 -->
        <el-form-item>
            <el-select size="medium" v-model="operateType" placeholder="选择商品类型">
                <el-option style="width:200px;" v-for="item in operateOptions" :key="item" :value="item" :label="item">
                </el-option>
            </el-select>
        </el-form-item>

        <el-form-item label="商品价格" prop="Price">
            <el-input v-model.number="ruleForm.Price"></el-input>
        </el-form-item>

        <el-form-item label="商品名称" prop="goodsName">
            <el-input v-model="ruleForm.goodsName"></el-input>
        </el-form-item>

        <el-form-item label="商品图片" prop="image">
            <el-upload action="#" :auto-upload="false" :show-file-list="false" :on-change="handleFileChange"
                accept="image/*">
                <el-button slot="trigger" size="small" type="primary">选择图片</el-button>
                <div slot="tip" class="el-upload__tip">建议上传 500x500 像素的JPG/PNG文件</div>
            </el-upload>
            <img v-if="ruleForm.image" :src="ruleForm.image" class="preview-image" alt="商品预览">
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="submitForm">立即创建</el-button>
            <el-button @click="resetForm">重置</el-button>
        </el-form-item>
    </el-form>
</template>

<script>
import { AddGoods, getHostKey, getGoodId } from '@/api/admin/Goods'
import request from '@/utils/request'
import { getStoreId } from '@/api/admin/store'
export default {
    data() {
        return {
            ruleForm: {
                GoodsId: '',
                goodsName: '',
                Price: null,
                image: '',  // 存储服务器返回的图片地址
                status: '1',   // 默认状态
                sellerID: getStoreId()    // 根据业务需求保留
            },
            operateOptions: [],
            operateType: '',
            rules: {
                goodsName: [
                    { required: true, message: '请输入商品名称', trigger: 'blur' },
                    { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
                ],
                Price: [
                    { required: true, message: '请输入价格', trigger: 'blur' },
                    { type: 'number', message: '必须为数字值', trigger: 'blur' }
                ]
            }
        }
    },
    methods: {
        // 文件选择处理
        async handleFileChange(file) {
            try {
                // 生成预览图
                const previewURL = URL.createObjectURL(file.raw)
                this.ruleForm.image = previewURL

                // 上传到服务器
                const serverUrl = await this.uploadImageToServer(file.raw)

                // 更新为服务器返回的真实URL
                this.ruleForm.image = serverUrl
            } catch (error) {
                console.error('图片处理失败:', error)
                this.$message.error('图片处理失败')
            }
        },

        // 图片上传方法
        async uploadImageToServer(file) {
            const formData = new FormData()
            formData.append('file', file)
            formData.append('goodsName', this.ruleForm.goodsName)

            const response = await request.post('/common/upload', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            })

            if (!response.data.data) {
                throw new Error('未获取到图片地址')
            }
            return response.data.data
        },

        // 表单提交
        async submitForm() {
            try {
                // 验证必填项
                if (!this.ruleForm.image) {
                    this.$message.warning('请上传商品图片')
                    return
                }
                // 提交数据
                console.log('this.ruleForm', this.ruleForm);

                const { data } = await AddGoods(this.ruleForm)

                if (data === 1) {
                    this.$message.success('商品添加成功')
                    this.$router.go(-1)
                }
            } catch (error) {
                console.error('提交失败:', error)
                this.$message.error('商品添加失败: ' + (error.response?.data?.msg || '服务器错误'))
            }
        },

        // 生成商品ID
        async generateGoodsId() {
            const storeName = localStorage.getItem('StoreName') || 'default'
            const id = await getGoodId(this.operateType, this.ruleForm.goodsName)
            return `${storeName}_${this.operateType}_${id}`
        },

        // 初始化商品类型
        GetHostKey() {
            getHostKey().then(res => {
                this.operateOptions = res.data || []
            })
        },

        // 重置表单
        resetForm() {
            this.$refs.ruleForm.resetFields()
            this.ruleForm.image = ''
        }
    },
    mounted() {
        this.GetHostKey()
    }
}
</script>

<style scoped>
.el-form {
    width: 800px;
    margin: 20px auto;
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.preview-image {
    display: block;
    margin-top: 10px;
    max-width: 200px;
    max-height: 200px;
    border: 1px solid #eee;
    border-radius: 4px;
    padding: 5px;
}

.el-upload__tip {
    color: #999;
    font-size: 12px;
    margin-top: 5px;
}
</style>